# -*- coding:UTF-8 -*-
import copy
import xml
import json
from middles import build_middle
from collections import OrderedDict


class Module(object):
    loop = False
    enable = False
    have_io = False  # IO模型本身就是IO、不需要其他IO、如果需要多重IO，则需要手动修改
    response_body = []
    
    def __init__(self, mod):
        self.load_event = None
        self.name = mod.getElementsByTagName('name')[0].firstChild.data  # 应用的名称
        self.num = int(mod.getElementsByTagName('num')[0].firstChild.data)  # 循环次数
        self.id = mod.getElementsByTagName('id')[0].firstChild.data  # 这是第几个
        cmds = mod.getElementsByTagName('command')  # 这是命令字典，将获得的命名转换为可用命令
        self.cmd_map = OrderedDict()
        for cmd in cmds:
            key = cmd.getElementsByTagName('active')[0].firstChild.data
            value = (
                cmd.getElementsByTagName('key')[0].firstChild.data,
                cmd.getElementsByTagName('value')[0].firstChild.data)
            if self.cmd_map.get(key) == None:
                self.cmd_map[key] = []
            self.cmd_map[key].append(value)
        
        self.io_m = mod.getElementsByTagName('io_m')[0].firstChild.data  # IO模型，如果不是IO模块，他的开关可以设置是否受到IO模块的影响
        self.have_io = True
        # self.customer = mod.getElementsByTagName('customer')[0].firstChild.data
        self.pathEle = mod.getElementsByTagName('path')[0]
        self.path = self.pathEle.firstChild.data  # 来源路径
        self.request = mod.getElementsByTagName('request')[0].firstChild.data
        if self.request != "Null":
            self.request_key = mod.getElementsByTagName('request')[0].getAttribute('key')
            self.request_customer = mod.getElementsByTagName('request')[0].getAttribute('customer')
            self.request_value = mod.getElementsByTagName('request')[0].getAttribute('value')
        self.type = mod.getElementsByTagName('type')[0].firstChild.data
        self.req_data = ""
        from customer import customer_build
        self.customer = customer_build(self.request_customer)
        if self.customer == None:
            return
        self.customer.config(self.pathEle)
    
    def print_msg(self, msg):
        msg = ' ' + msg  # 不用再在头上加空格了
        msg = "The Module " + self.name + '----' + self.id + '/' + self.num + msg + '\n'
        print(msg)
        return
    
    def is_enable(self, bag):
        if self.io_m == '0':
            print("Module havn't io Module")
            self.enable = True
        else:
            self.io_m = bag.find_module(self.io_m)  # 将id实例化为类
            io_model = bag.find_module(self.io_m)
            if io_model.enable:
                self.enable = True
            else:
                self.enable = False
        return True
    
    def set_enable(self):
        if self.have_io:
            self.enable = self.io_m.is_enable()
        else:
            self.enable = True
        if self.enable:
            self.customer.config(self.pathEle)
    
    def run(self, event):
        cmds = self.cmd_map.get(event.active)
        if cmds == None:
            return
        for cmd in cmds:
            try:
                middlev = build_middle(self.request_value)
                resp = self.customer.run(cmd[0], middlev, event=event, path=self.path, cmd=cmd[1])
                if len(self.response_body) > 10:
                    self.response_body.pop(0)
                if resp:
                    self.response_body.append(resp)
            except Exception as e:
                continue
        self.num -= 1
    
    def happen_event(self, event):  # 监听事件
        self.bag = event.bag
        self.load_event = copy.deepcopy(event)
        self.run(self.load_event)
        print("Module have run")
        return self.response()
    
    def loop_run(self, num):
        try:
            self.run(self.load_event)
        except Exception as e:
            print(e)
        print("Loop Run!!!")
        return self.response()
    
    def get_loop(self):
        print("Loop num: {}".format(self.num))
        if int(self.num) > 0:
            self.num -= 1
            return True
        if int(self.num) == 65536:
            return True
        else:
            return False
    
    def set_loop(self, num):
        self.num = num
    
    def response(self):
        print("self.bag =" + self.bag)
        print("self.name =" + self.name)
        mod_map = {}
        from init.fileinit import device_key
        mod_map["path"] = self.load_event.bagPath
        mod_map["write"] = self.response_body
        mod_map["name"] = self.name
        mod_json = json.dumps(mod_map, ensure_ascii=True)
        return mod_json
